import 'package:flutter/material.dart';
import 'package:flutter_09_game/base/controller/base_controller.dart';
import 'package:flutter_09_game/config/app_config.dart';
import 'package:flutter_09_game/config/app_routes.dart';
import 'package:flutter_09_game/config/history_route_ovserver.dart';
import 'package:flutter_09_game/generated/assets.dart';
import 'package:flutter_09_game/generated/locales.g.dart';
import 'package:flutter_09_game/http/http_export.dart';
import 'package:flutter_09_game/pages/game/game_detail/game_detail_logic.dart';
import 'package:flutter_09_game/pages/game/game_detail/models/model_quick_bet_set.dart';
import 'package:flutter_09_game/pages/game/game_detail/widgets/widget_quick_bet_setting.dart';
import 'package:flutter_09_game/user/app_user_manager.dart';

import 'package:flutter_09_game/utils/loading/loading_utils.dart';
import 'package:flutter_09_game/utils/log/utils_log.dart';
import 'package:flutter_09_game/utils/sound/sound_manager.dart';
import 'package:flutter_09_game/utils/utils_other.dart';
import 'package:flutter_09_game/widgets/dialog/common_normal_sheet.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

class GameDetailPageLogic extends BaseController
    with GetTickerProviderStateMixin {
  // 投注金额控制器
  TextEditingController amountController = TextEditingController();

  ScrollController scrollController = ScrollController();

  RxBool selectOddRx = false.obs;

  List<String> symbols =
      AppUserManager().walletList.map((f) => f.symbol ?? '').toList();

  // late RxString symbolRx = symbols.isNotEmpty ? symbols.first.obs : ''.obs;

  // List<int> inputs = [20, 100, 500, 1000, 5000];

  RxBool canPlaceBetRx = false.obs;

  RxList<ModelQuickBetSet> quickBetRowsRx = RxList(AppConfig.quickDefines);

  // 选中的快捷金额按钮索引
  Rxn<int> selectedQuickBetIndexRx = Rxn<int>();

  Worker? wallerWorker;
  Worker? gameRoundWorker;

  @override
  void onReady() {
    super.onReady();

    WidgetsBinding.instance.addPostFrameCallback((_) {
      _scrollToEnd();
    });
    gameRoundWorker = ever(Get.find<GameDetailLogic>().gameRoundRx, (value) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        _scrollToEnd();
      }); /**/
    });
    wallerWorker = ever(AppUserManager().currentWalletRx, (val) {
      // clog('dalksdjalksjdlkasjdlasld');
      getQuickBetSetting();
    });
  }

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    amountController.addListener(textControllerListener);

    // 初始化音效管理器
    SoundManager().initialize();
    getQuickBetSetting();
  }

//  Assets.gameVolumeClose,
  textControllerListener() {
    // 播放按键音效

    canPlaceBetRx.value = amountController.text.isNotEmpty;

    // 检查当前输入值是否与选中的快捷金额匹配，不匹配则清除高亮
    if (selectedQuickBetIndexRx.value != null) {
      final selectedAmount =
          quickBetRowsRx[selectedQuickBetIndexRx.value!].amount ?? 0;
      final currentAmount =
          (int.tryParse(amountController.text) ?? 0) * 1000000;
      if (selectedAmount != currentAmount) {
        selectedQuickBetIndexRx.value = null;
      }
    }
  }

  // 选择快捷金额
  void selectQuickBet(int index, int amount) {
    selectedQuickBetIndexRx.value = index;
    amountController.text = (amount ~/ 1000000).toString();
  }

  @override
  void onClose() {
    amountController.dispose();
    wallerWorker?.dispose();
    gameRoundWorker?.dispose();
    // coinController.dispose();
    super.onClose();
    scrollController.dispose();
  }

  /// 滚动到最右边
  void _scrollToEnd() {
    if (scrollController.hasClients) {
      scrollController.animateTo(
        scrollController.position.maxScrollExtent,
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeOut,
      );
    }
  }

  postGameRoundJoin() async {
    GameDetailLogic gameDetailLogic = Get.find<GameDetailLogic>();
    // Get.find<GameDetailLogic>()
    if (gameDetailLogic.proShowBetRx.value == true) {
      gameDetailLogic.showStopGame();
      return;
    }
    if (canPlaceBetRx.value == false) {
      return;
    }

    if (gameDetailLogic.soundRx.value) {
      SoundManager().playButtonSound();
    }

    HttpResponse response = await HttpManager().post(
      API.postGameRoundJoin,
      // fromJson: .fromJson,
      params: {
        'amount': (int.tryParse(amountController.text) ?? 0) * 1000000,
        'symbol': AppUserManager().currentWalletRx.value.symbol,
        'game_id': gameDetailLogic.gameId,
        'round': gameDetailLogic.rightHistoryRx.value?.round,
        // == null ? gameLogic.rightHistoryRx.value?.round
        'direction': selectOddRx.value ? 2 : 1,
      },
    );

    if (response.isSuccess) {
      LoadingUtils.showToast(LocaleKeys.betSuccess.tr);
      amountController.text = '';
      AppUserManager().loadWalletData();
      Get.find<GameDetailLogic>().getGameDataSource();
    }
  }

  postQuickBetSetting(List<ModelQuickBetSet> rows) async {
    HttpResponse response = await HttpManager().post(
      API.getQuickBetSetting,

      // fromJson: ModelQuickBetSet.fromJson,
      params: {
        'game_id': Get.find<GameDetailLogic>().gameId,
        'symbol': AppUserManager().currentWalletRx.value.symbol,
        'amount': rows.map((item) => item.amount).toList()
      },
    );

    if (response.isSuccess) {
      LoadingUtils.showToast(LocaleKeys.setSuccess.tr);
      getQuickBetSetting();
      routeHistoryObserver.removeName(CommonNormalSheet.name);
    }
  }

  getQuickBetSetting() async {
    HttpResponse response = await HttpManager().get(
      API.getQuickBetSetting,
      fromJson: ModelQuickBetSet.fromJson,
      params: {
        'game_id': Get.find<GameDetailLogic>().gameId,
        'symbol': AppUserManager().currentWalletRx.value.symbol,
      },
    );
    if (response.isSuccess) {
      // [].isNotEmpty
      if (response.data.isNotEmpty) {
        quickBetRowsRx.value = response.data;
      } else {
        quickBetRowsRx.value = AppConfig.quickDefines;
      }
      // return response.data;
    }
  }

  showBetSetting() {
    // clog('dalksjdkls   ${quickBetRowsRx.length}');

    CommonNormalSheet(
      title: LocaleKeys.setQuickAmount.tr,
      child: SizedBox(
        height: 450.h,
        // child: HomeGameplayTutorialListPage(
        //   type: (gameActive.game?.id ?? '').toString(),
        //   gameActive: gameActive,
        // ),

        child: WidgetQuickBetSetting(
          rows: quickBetRowsRx.toList(),
          logic: this,
          gameLogic: Get.find<GameDetailLogic>(),
        ),
      ),
    ).show().then((value) {
      if (Get.find<GameDetailLogic>().checkForbidBet()) {
        Get.find<GameDetailLogic>().checkShowStopGame();
      }
    });
  }
}
